package com.share.example.selenium.service.hzhc.hm;

import com.alibaba.fastjson.JSON;
import com.share.common.utils.DelayUtil;
import com.share.example.selenium.model.hzhc.hm.HmUserInfo;
import com.share.example.selenium.service.AbsDriver;
import com.share.example.selenium.utils.DriverUtil;
import com.share.example.selenium.utils.ElementUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Data
@Slf4j
@Service
public class HcxxHmLoginService extends AbsDriver {
    private final String LOGIN_URL_PRE = "https://mh.ihanchen.com/#/user/login";
    private final String LOGIN_SUCCESS_FORWORD_URL_PRE = "https://mh.ihanchen.com/#/WorkPlatformPage/index";

    @Autowired
    protected WebDriver driver;

    @Value("${rootUrl.ocr}")
    private String ocrUrl;

    @Override
    public void reInitDriver(WebDriver driver) {
        this.driver = driver;
    }

    //门户网站登录
    public HmUserInfo fixLoginform(String account, String password) {
        //1.打开首页
        String url = "https://mh.ihanchen.com/#/user/login";
        log.info("正在打开京发云门户中心首页,url={}", url);
        driver.get(url);
        DelayUtil.sleepRangSecond(2, 5);

        String currentUrl = driver.getCurrentUrl();
        if (!currentUrl.contains(LOGIN_URL_PRE)) {
            log.info("当前不是登录表单的页面,currentUrl={}", currentUrl);
            return null;
        }

        //1.填写账号
        if (StringUtils.isEmpty(account)) {
            account = "13267158278";
        }
        log.info("即将填写账号信息,account={}", account);
        WebElement ele_username = driver.findElement(By.id("username"));
        ElementUtil.inputValue(ele_username, account, 100, 800);

        //2.填写密码
        if (StringUtils.isEmpty(password)) {
            password = "1qaz@WSX";
        }
        log.info("即将填写密码信息,password={}", password);
        WebElement ele_password = driver.findElement(By.id("password"));
        ElementUtil.inputValue(ele_password, password, 100, 800);


        //3.登录失败多次,需要重试（验证码识别出来了,但是不正确）
        int login_count = 1;
        String userInfo = null;
        do {
            //3.获取验证码图片
            WebElement divImage = driver.findElement(By.xpath("//*[@id=\"root\"]/div/div/div/div[2]/div/div/div/form/div[1]/div[4]/div/div/span/div/div[2]/img"));
            String code = ElementUtil.getImageCode(ocrUrl,divImage, 5, 3, "base64");

            //4.填写验证码
            WebElement ele_code = driver.findElement(By.id("code"));
            ele_code.clear();//清除历史值
            if (StringUtils.isEmpty(code)) {
                String value = ele_code.getAttribute("value");
                while (StringUtils.isEmpty(value) || value.length() != 5) {
                    value = ele_code.getAttribute("value");
                    log.info("请手动输入验证码,当前填充code={}", value);
                    DelayUtil.sleepSecond(3);
                }
            } else {
                ElementUtil.inputValue(ele_code, code, 100, 800);
                DelayUtil.sleepSecond(3);
            }

            //5.点击登录
            log.info("第{}次登录,account={},password={},code={}", login_count, account, password, code);
            WebElement loginButton = driver.findElement(By.xpath("//*[@id=\"root\"]/div/div/div/div[2]/div/div/div/form/div[3]/div/div/div/span/button"));
            loginButton.submit();

            //6.点击之后必须等待---页面加载需要时间（还是当前target）
            DelayUtil.sleepRangSecond(3, 10);

            String forward_currentUrl = driver.getCurrentUrl();
            if (forward_currentUrl.contains(LOGIN_SUCCESS_FORWORD_URL_PRE)) {
                login_count = 10; //将直接退出

                userInfo = DriverUtil.getLocalStorage(driver, "sword-current-user");
                log.info("单点登录---用户信息={}", userInfo);
            } else {
                login_count++;
            }
        } while (login_count < 4);


        if (login_count == 10) {
            return JSON.parseObject(userInfo, HmUserInfo.class);
        } else {
            log.info("登录失败,currentUrl={}", currentUrl);
            return null;
        }
    }

    public static void main(String[] args) {
        HmUserInfo hmUserInfo = new HcxxHmLoginService().fixLoginform("13267158278", "1qaz@WSX");
        System.out.println(JSON.toJSON(hmUserInfo));
    }
}
